package com.dmwork.service.interaction.mq.receiver;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dmwork.common.base.result.ExceptionUtils;
import com.dmwork.service.interaction.entity.Feed;
import com.dmwork.service.interaction.mq.sender.MessageSender;
import com.dmwork.service.interaction.service.FeedService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Transactional
@Component
public class MessageReceiver {

    @Autowired
    private FeedService feedService;
    @Autowired
    private MessageSender messageSender;

    /**
     * 作品发布后，创建一条动态
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(
                            value = "${spring.rabbitmq.custom.receiver.message-receiver.on-work-publish-message-receive.queue.name}",
                            durable = "${spring.rabbitmq.custom.receiver.message-receiver.on-work-publish-message-receive.queue.durable}",
                            arguments = {
                                    @Argument(
                                            name = "x-dead-letter-exchange",
                                            value = "${spring.rabbitmq.custom.receiver.message-receiver.on-work-publish-message-receive.x-dead-letter-exchange}"
                                    ),
                                    @Argument(
                                            name = "x-dead-letter-routing-key",
                                            value = "${spring.rabbitmq.custom.receiver.message-receiver.on-work-publish-message-receive.x-dead-letter-routing-key}"
                                    )
                            }
                    ),
                    exchange = @Exchange(
                            value = "${spring.rabbitmq.custom.receiver.message-receiver.exchange.name}",
                            type = "${spring.rabbitmq.custom.receiver.message-receiver.exchange.type}",
                            durable = "${spring.rabbitmq.custom.receiver.message-receiver.exchange.durable}",
                            ignoreDeclarationExceptions = "${spring.rabbitmq.custom.receiver.message-receiver.exchange.ignore-declaration-exceptions}"
                    ),
                    key = {"${spring.rabbitmq.custom.receiver.message-receiver.on-work-publish-message-receive.key}"}
            )
    })
    @RabbitHandler
    public void onWorkPublishMessageReceive(Message<Map<String, Object>> message, Channel channel) throws IOException {
        try {
            //创建动态信息
            Map<String, Object> payload = message.getPayload();
            log.info(payload.toString());
            Feed feed = new Feed();
            feed.setCustomerId((String) payload.get("customerId"));
            feed.setWorkId((String) payload.get("workId"));
            feed.setContent((String) payload.get("content"));
            feedService.save(feed);

            //向消息系统发送新动态
            messageSender.sendFeedMessage((String) payload.get("customerId"), feed.getId(), new HashMap<>());
            //返回确认
            long deliveryTag = (long) message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            ExceptionUtils.getMessage(e);
            long deliveryTag = (long) message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
            channel.basicNack(deliveryTag, false, false);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
    }

    /**
     * 作品删除后，将该作品发布时发送的投稿动态也删除
     * @param message
     * @param channel
     */
    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(
                            value = "${spring.rabbitmq.custom.receiver.message-receiver.on-work-publish-feed-remove-message-receive.queue.name}",
                            durable = "${spring.rabbitmq.custom.receiver.message-receiver.on-work-publish-feed-remove-message-receive.queue.durable}",
                            arguments = {
                                    @Argument(
                                            name = "x-dead-letter-exchange",
                                            value = "${spring.rabbitmq.custom.receiver.message-receiver.on-work-publish-feed-remove-message-receive.x-dead-letter-exchange}"
                                    ),
                                    @Argument(
                                            name = "x-dead-letter-routing-key",
                                            value = "${spring.rabbitmq.custom.receiver.message-receiver.on-work-publish-feed-remove-message-receive.x-dead-letter-routing-key}"
                                    )
                            }
                    ),
                    exchange = @Exchange(
                            value = "${spring.rabbitmq.custom.receiver.message-receiver.exchange.name}",
                            type = "${spring.rabbitmq.custom.receiver.message-receiver.exchange.type}",
                            durable = "${spring.rabbitmq.custom.receiver.message-receiver.exchange.durable}",
                            ignoreDeclarationExceptions = "${spring.rabbitmq.custom.receiver.message-receiver.exchange.ignore-declaration-exceptions}"
                    ),
                    key = {"${spring.rabbitmq.custom.receiver.message-receiver.on-work-publish-feed-remove-message-receive.key}"}
            )
    })
    @RabbitHandler
    public void onWorkPublishFeedRemoveMessageReceive(Message<Map<String, Object>> message, Channel channel) throws IOException {
        try {
            Map<String, Object> payload = message.getPayload();
            String workId= (String) payload.get("workId");
            feedService.remove(new QueryWrapper<Feed>().eq("work_id", workId));
            log.info("作品投稿动态已删除。。。");
            long deliveryTag= (long) message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            ExceptionUtils.getMessage(e);
            long deliveryTag= (long) message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
            channel.basicNack(deliveryTag, false, false);
        }
    }

}
